<template>
  <div :class="{fullscreen:fullscreen}" class="tinymce-container editor-container">
    <textarea :id="tinymceId" class="tinymce-textarea" />
    <!-- <div class="editor-custom-btn-container">
      <editorImage color="#1890ff" class="editor-upload-btn" @successCBK="imageSuccessCBK" />
    </div>-->
  </div>
</template>

<script>
/* import editorImage from './components/editorImage'*/
import plugins from './plugins'
import toolbar from './toolbar'

/* import { upPosterByArt } from '@/api/media'*/

export default {
  name: 'Tinymce',
  /* components: { editorImage },*/
  props: {
    id: {
      type: String,
      default: function() {
        return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
      }
    },
    isImg: {
      type: Boolean,
      default: function() {
        return true
      }
    },
    value: {
      type: String,
      default: ''
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return []
      }
    },
    menubar: {
      type: String,
      default: 'file edit insert view format table help'
    },
    height: {
      type: Number,
      required: false,
      default: 360
    }
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      languageTypeList: {
        'en': 'en',
        'zh': 'zh_CN'
      },
      switchData: ''
    }
  },
  computed: {
    language() {
      return 'zh_CN' // this.languageTypeList[this.$store.getters.language]
    }
  },
  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(val || ''))
      }
    },
    language() {
      this.destroyTinymce()
      this.$nextTick(() => this.initTinymce())
    }
  },
  mounted() {
    this.initTinymce()
  },
  activated() {
    this.initTinymce()
  },
  deactivated() {
    this.destroyTinymce()
  },
  destroyed() {
    this.destroyTinymce()
  },
  methods: {
    initTinymce() {
      const _this = this
      window.tinymce.init({
        language: this.language,
        selector: `#${this.tinymceId}`,
        height: this.height,
        body_class: 'panel-body ',
        image_dimensions: true,
        // 是否允许上传图片
        images_upload_url: !!this.isImg,
        // 图片和表格是否开启在编辑器内部缩放
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        // 隐藏富文本编辑器组件的商标消息” Powered by TinyMCE”
        branding: false,
        paste_as_text: true,
        // 右键菜单
        contextmenu: 'bold cut copy paste save preview image',
        // 插件
        plugins: this.isImg ? plugins.all : plugins.noImg,
        forced_root_block: this.isImg ? 'p' : '',
        //  如果在空的内部块元素中按enter键，则此选项允许您拆分当前容器块元素
        end_container_on_empty_block: true,
        // 开启默认过滤器
        paste_enable_default_filters: false,
        // 此设置控制如何筛选从Microsoft Word粘贴的内容
        powerpaste_word_import: 'clean',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        // 此选项允许您在默认bullist工具栏控件中包含特定的无序列表项标记
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        // 指定跨域地址
        imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
        // 链接默认打开方式
        default_link_target: '_blank',
        fontsize_formats: '8px 12px 16px 18px 20px 24px 26px 28px 30px 36px',
        // 是否允许禁用链接对话框中的链接标题输入字段
        link_title: false,
        // 此选项允许您在用户按下键盘tab键时强制TinyMCE插入三个实体
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            this.hasChange = true
            this.$emit('input', editor.getContent())
          })
        },
        importword_handler: (editor, files, next) => {
          const file_name = files[0].name
          if (file_name.substr(file_name.lastIndexOf('.') + 1) === 'docx') {
            editor.notificationManager.open({
              text: '正在转换中...',
              type: 'info',
              closeButton: false
            })
            next(files)
          } else {
            editor.notificationManager.open({
              text: '目前仅支持docx文件格式，若为doc，请将扩展名改为docx',
              type: 'warning'
            })
          }
        },
        images_upload_handler: (blobInfo, success, failure, progress) => {
          if (this.isImg) { // 如果是可以上传图片
            const file = blobInfo.blob()
            if (file.size / 1024 < 100) {
              const formData = new FormData()
              formData.append('file', blobInfo.blob(), blobInfo.blob().name)
              // 项目中的 图片服务器 保存在store中
              const url = this.$store.state.app.imgbase ? this.$store.state.app.imgbase : ''
              const upPosterByArt = '' // 上传图片接口请求方法
              // 上传图片
              return new Promise((resolve, reject) => {
                upPosterByArt(formData).then(response => {
                  if (response.errorMsg === '成功') {
                    this.$message.success('图片上传成功')
                    const img = new Image()
                    console.log(url + response.data)
                    img.src = url + response.data
                    const _this = this
                    img.onload = function() {
                      // 可以在这里判断 上传图片的尺寸是否合乎要求 img.height  img.width
                      _this.$emit('imgSizeFun', { url: img.src, sizeUrl: 'height=' + img.height + ' width=' + img.width })
                    }
                    // 上传成功返回路径
                    success(url + response.data)
                  } else {
                    this.$message.error('图片上传失败')
                    resolve()
                  }
                }).catch(error => {
                  reject(error)
                })
              })
            } else {
              let name = file.name
              if (!name) {
                name = '文件中有'
              }
              failure(`上传${name}图片超过100KB，请重新选择图片！`)
            }
          }
        },
        setup(editor) {
          editor.on('FullscreenStateChanged', (e) => {
            _this.fullscreen = e.state
          })
        }
      })
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId)
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }

      if (tinymce) {
        tinymce.destroy()
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value)
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent()
    },
    imageSuccessCBK(arr) {
      const _this = this
      arr.forEach(v => {
        window.tinymce.get(_this.tinymceId).insertContent(`<img class="wscnph" src="${v.url}" >`)
      })
    }
  }
}
</script>

<style scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}
.tinymce-container>>>.mce-fullscreen {
  z-index: 10000;
}
.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}
.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}
.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}
.editor-upload-btn {
  display: inline-block;
}
</style>
